<?php

/**
 * Yii Controller FilesController
 *
 * @author <KTD SOFT>
 * @since May 14, 2013 - 10:20:30 PM
 */
class FilesController extends BackController
{

    public $root_upload_path = "files";

    function actionIndex()
    {
        $base_url = Yii::app()->baseUrl;
        $files    = $this->_searchDir("./", $this->root_upload_path, "", -1);

        $this->layout = '//layouts/iframe';
        $this->render('index', array(
            'files'    => $files,
            'path'     => $this->root_upload_path,
            'base_url' => $base_url
        ));
    }

    function actionSearchDir()
    {
        $p     = isset($_POST["path"]) ? $_POST["path"] : "";
        $f     = isset($_POST["filter"]) ? $_POST["filter"] : "";
        $files = $this->_searchDir("./", $p, $f, -1);

        $this->layout = 'blank';
        if ($f == 'folder')
            $this->render('folders', array('files' => $files));
        else
            $this->render('files', array('files' => $files));
    }

    private function _searchDir($base_dir = "./", $p = "", $f = "", $allowed_depth = -1)
    {
        $contents = array();

        $base_dir = trim($base_dir);
        $p        = trim($p);
        $f        = trim($f);

        if ($base_dir == "")
            $base_dir = "./";
        if (substr($base_dir, -1) != "/")
            $base_dir.="/";
        $p        = str_replace(array("../", "./"), "", trim($p, "./"));
        $p        = $base_dir . $p;

        if (!is_dir($p))
            $p = dirname($p);
        if (substr($p, -1) != "/")
            $p.="/";

        if ($allowed_depth > -1)
        {
            $allowed_depth = count(explode("/", $base_dir)) + $allowed_depth - 1;
            $p             = implode("/", array_slice(explode("/", $p), 0, $allowed_depth));
            if (substr($p, -1) != "/")
                $p.="/";
        }

        $filter = ($f == "") ? array() : explode(",", strtolower($f));

        $files = @scandir($p);
        if (!$files)
            return array("contents" => array(), "currentPath" => $p);

        for ($i = 0; $i < count($files); $i++)
        {
            $fName = $files[$i];
            $fPath = $p . $fName;

            $isDir = is_dir($fPath);
            $add   = false;
            $fType = "folder";

            if (!$isDir)
            {
                $ft    = strtolower(substr($files[$i], strrpos($files[$i], ".") + 1));
                $fType = $ft;
                if ($f != "")
                {
                    if (in_array($ft, $filter))
                        $add = true;
                }else
                {
                    $add = true;
                }
            }
            else
            {
                if ($fName == ".")
                    continue;
                $add = true;

                if ($f != "")
                {
                    if (!in_array($fType, $filter))
                        $add = false;
                }

                if ($fName == "..")
                {
                    if ($p == $base_dir)
                    {
                        $add = false;
                    }
                    else
                        $add = true;

                    $tempar = explode("/", $fPath);
                    array_splice($tempar, -2);
                    $fPath  = implode("/", $tempar);
                    if (strlen($fPath) <= strlen($base_dir))
                        $fPath  = "";
                }
            }

            if ($fPath != "")
                $fPath      = substr($fPath, strlen($base_dir));
            if ($add)
                $contents[] = array("fPath" => $fPath, "fName" => $fName, "fType" => $fType);
        }

        $p = (strlen($p) <= strlen($base_dir)) ? $p = "" : substr($p, strlen($base_dir));
        return array("contents" => $contents, "currentPath" => $p);
    }

    /**
     * Hàm xử lý upload
     * @return string chuỗi url sau khi upload xong
     */
    public function do_upload()
    {
        $this->checkAccess('update');

        Yii::import('application.vendors.*');
        require_once('resize-class.php');

        $file   = $_FILES['Upload'];
        $folder = "uploads/";
        $upload = array();
        foreach ($file['name'] as $field => $fileName)
        {
            if ($fileName == '')
                continue;

            $todayFolder = "$this->conName/" . date("Y/md/");

            if (!is_dir($folder . $todayFolder))
                @mkdir($folder . $todayFolder, 0777, TRUE);

            $newName     = time() . "_" . basename($fileName);
            $target_path = $todayFolder . $newName;
            if (move_uploaded_file($file['tmp_name'][$field], $folder . $target_path))
            {
                $upload[$field] = $target_path;
            }

            $thumbName = "small_" . $newName;
            $resizeObj = new resize($folder . $target_path);
            $resizeObj->resizeImage(175, 114, 'crop');
            $resizeObj->saveImage($folder . $todayFolder . $thumbName);

            $thumbName = "medium_" . $newName;
            unset($resizeObj);
            $resizeObj = new resize($folder . $target_path);
            $resizeObj->resizeImage(250, 162, 'crop');
            $resizeObj->saveImage($folder . $todayFolder . $thumbName);

            $thumbName = "large_" . $newName;
            unset($resizeObj);
            $resizeObj = new resize($folder . $target_path);
            $resizeObj->resizeImage(875, 570, 'crop');
            $resizeObj->saveImage($folder . $todayFolder . $thumbName);
        }

        return $upload;
    }

    /**
     * Hàm xử lý upload ảnh
     * @return string chuỗi url sau khi upload xong
     */
    public function actionUpload()
    {
        $success = false;
        $mess    = 'Không upload được ảnh!';
        if (@$_FILES['file'])
        {
            $file   = $_FILES['file'];
            $folder = isset($_POST['folder']) ? $_POST['folder'] : $this->root_upload_path;

            if (move_uploaded_file($file['tmp_name'], $folder . "/" . date('d') . '-' . date('m') . '-' . date('Y') . '-' . MyUtil::vn_url_filename($file['name'])))
            {
                $success = true;
                $mess    = 'Upload ảnh thành công!';
            }
        }

        $return = array(
            'success' => $success,
            'mess'    => $mess,
        );
        echo json_encode($return);
        die;
    }

    function actionRename()
    {
        
    }

    function actionNewFolder()
    {
        $f = isset($_POST['folder']) ? $_POST['folder'] : "./$this->root_upload_path";
        $n = isset($_POST['name']) ? $_POST['name'] : "ThuMucMoi";

        @mkdir("$f/$n", 0777, TRUE);
    }

    function actionRemove()
    {
        if (isset($_POST['path']))
        {
            $path = str_replace("..", "", $_POST['path']);
            $file = "./$path";
            if (file_exists($file))
            {
                if (is_dir($file) && $file != './files/' && $file != './' && $file != '/' && $file != '')
                    $this->_deleteDirectory($file);
                elseif (is_file($file))
                    unlink($file);
            }
        }
    }

    private function _deleteDirectory($dir)
    {
        if (!file_exists($dir))
            return true;
        if (!is_dir($dir) || is_link($dir))
            return unlink($dir);
        foreach (scandir($dir) as $item)
        {
            if ($item == '.' || $item == '..')
                continue;
            if (!$this->_deleteDirectory($dir . "/" . $item))
            {
                chmod($dir . "/" . $item, 0777);
                if (!$this->_deleteDirectory($dir . "/" . $item))
                    return false;
            };
        }
        return rmdir($dir);
    }

}

/** 
 * End file FilesController
 */
